package com.enqualcomm.kids.mvp.question;

import android.media.MediaPlayer;

import java.io.IOException;

/**
 * Created by Sunzhigang on 2016/3/7.
 */
public class QuestionMediaPlayManage {
    private MediaPlayer mediaPlayer;

    QusetionPresenter presenter;

    public QuestionMediaPlayManage(QusetionPresenter presenter) {
        mediaPlayer = new MediaPlayer();
        this.presenter = presenter;
    }

    int iPlayCount = 0;

    public void playMedia(String musicPath, final boolean isLoop) {
        iPlayCount = 0;
        try {
            mediaPlayer.setDataSource(musicPath);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (isLoop) {
                        playAgainVoice(mp);
                    } else {
                        mp.reset();
                        presenter.stopFrameAnimation();
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playAgainVoice(MediaPlayer mp) {
        iPlayCount++;
        if (iPlayCount == 2) {
            mp.reset();
            presenter.stopFrameAnimation();
        }else if (iPlayCount==1){
            mp.start();
        }
    }

    //    public void playMedia(String musicPath) {
//        try {
//            mediaPlayer.setDataSource(musicPath);
//            mediaPlayer.prepareAsync();
//
//            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
//                @Override
//                public void onPrepared(MediaPlayer mp) {
//                    mp.start();
//                }
//            });
//            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//                @Override
//                public void onCompletion(MediaPlayer mp) {
//                    mp.reset();
//                }
//            });
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
    public void stopPlay() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.reset();
        }
    }

    public boolean isPlaying() {
        if (mediaPlayer != null) {
            return mediaPlayer.isPlaying();
        } else {
            return false;
        }

    }

    public void release() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
    }
}
